import re
from typing import Callable

from python_part.main_policy_database_member.ReadWriteClass import ReadWriteClass

from python_part.policy_receive.line_solver.line_solver_base import LineSolverBase

class SetSolver(LineSolverBase):
    def __init__(self,
        get_all_policy: Callable[[], tuple[dict, dict, dict]],
        update_entity_path_to_rwclass_id: Callable[[str, int], None],
        update_rwclass_id_to_rwclass: Callable[[int, ReadWriteClass], None],
        delete_entity_path_to_rwclass_id: Callable[[str], None],
        delete_rwclass_id_to_rwclass: Callable[[int], None]):

        super().__init__(get_all_policy, update_entity_path_to_rwclass_id, update_rwclass_id_to_rwclass,
                         delete_entity_path_to_rwclass_id, delete_rwclass_id_to_rwclass)
        self.pattern = re.compile(
            r"^set (owner_class_id|who_can_read_this|who_can_write_this) of ([1-9]\d*) by(\s[1-9]\d*,)* ([1-9]\d*)$")

        self.pattern_for_get_list = re.compile(r"[1-9]\d*")

    def check_is_this(self, line_content:str) -> bool:
        ans = self.pattern.match(line_content)
        if ans:
            return True
        return False

    def solve_one(self, line_content:str) -> bool:
        match = self.pattern.match(line_content)
        if match:
            set_witch_field = match.group(1)
            read_write_class_id = int(match.group(2))
            if self.get_all_policy()[1].get(read_write_class_id) is None:
                self.get_all_policy()[1][read_write_class_id] = ReadWriteClass()
                self.get_all_policy()[1][read_write_class_id].class_id = read_write_class_id
            if set_witch_field == 'owner_class_id':
                self.get_all_policy()[1][read_write_class_id].owner_class_id = int(match.group(4))
            elif set_witch_field == 'who_can_read_this':
                set_need_in = set(map(int, self.pattern_for_get_list.findall(line_content)[1:]))
                self.get_all_policy()[1][read_write_class_id].class_ids_can_read_this = set_need_in
            elif set_witch_field == 'who_can_write_this':
                set_need_in = set(map(int, self.pattern_for_get_list.findall(line_content)[1:]))
                self.get_all_policy()[1][read_write_class_id].class_ids_can_write_this = set_need_in
            else:
                return False
            return True

        return False

